package com.hongxun.design.jungong.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.activitys.BaseActivity;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.sqlite.bean.Bj;
import com.hongxun.design.sqlite.bean.OldBj;
import com.hongxun.design.sqlite.dao.BjDao;
import com.hongxun.design.sqlite.dao.OldBjDao;
import com.hongxun.design.ui.ScannerActivity;
import com.hongxun.design.ui.dialogstyle.LoadingDialog;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.utils.RecyclerViewUtils;
import com.hongxun.design.utils.SPUtils;
import com.hongxun.design.utils.StringUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;
import com.pop.android.common.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class BjListActivity extends BaseActivity {
    private HeadSecondControlPanel headsecond_layout;
    RecyclerView list1, list2;
    List<OldBj> oldList = new ArrayList<>();
    SuperAdapter<OldBj> oldAdapter;
    List<Bj> datas = new ArrayList<>();
    SuperAdapter<Bj> adapter;
    String proId = "", bxId = "";
    String old_code = "", new_code = "";
    OldBjDao oldDao;
    BjDao bjDao;
    TextView count1, count2;
    EditText search_content;
    Bj editBj;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bj_list);
        oldDao = new OldBjDao(this);
        bjDao = new BjDao(this);
        proId = MyApp.currProject.getProject_id();
        old_code = (String) SPUtils.get(this, "old_code", "");
        new_code = (String) SPUtils.get(this, "new_code", "");
        bxId = MyApp.currExploration.getExploration_id();
        initheader();
        getOldByCode();
        getBj();
    }


    void getOldByCode() {
        List<OldBj> list = oldDao.selectByCode(proId, old_code);
        oldList.addAll(list);
        oldAdapter.notifyDataSetChanged();

    }

    void getBj() {
        List<Bj> list2 = bjDao.getBjList(proId, bxId);
        datas.addAll(list2);
        adapter.notifyDataSetChanged();
        int count = datas.size();
        count2.setText("" + count);
    }

    private void initheader() {
        search_content = (EditText) findViewById(R.id.search_content);
        count1 = (TextView) findViewById(R.id.count);
        long count = oldDao.getCount(proId);
        count1.setText(count + "");
        count2 = (TextView) findViewById(R.id.count2);
        list1 = (RecyclerView) findViewById(R.id.list1);
        list1.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForVertical(this));
        list1.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        list1.setAdapter(oldAdapter = new SuperAdapter<OldBj>(R.layout.content_bjlist_old) {
            @Override
            public void bindView(ViewHolder viewHolder, final OldBj oldBj, int i) {
                ((TextView) viewHolder.getView(R.id.name)).setText(oldBj.getName());
                ((TextView) viewHolder.getView(R.id.code)).setText(oldBj.getCode());
                ((TextView) viewHolder.getView(R.id.bj_code)).setText(oldBj.getBjCode());
                viewHolder.getView(R.id.add).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setOld2New(oldBj);
                    }
                });
            }
        });
        oldAdapter.setData(oldList);
        list2 = (RecyclerView) findViewById(R.id.list2);
        list2.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForVertical(this));
        list2.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        list2.setAdapter(adapter = new SuperAdapter<Bj>(R.layout.content_bjlist_new) {
            @Override
            public void bindView(ViewHolder viewHolder, final Bj bj, int i) {
                ((TextView) viewHolder.getView(R.id.name)).setText(bj.getName());
                ((TextView) viewHolder.getView(R.id.code)).setText(bj.getCode());
                ((TextView) viewHolder.getView(R.id.bj_code)).setText(bj.getBj_new_code());
                viewHolder.getView(R.id.edit).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        editBj = bj;
                        Intent intent = new Intent(BjListActivity.this, BjEditeActivity.class);
                        intent.putExtra("data", bj);
                        startActivityForResult(intent, 2);
                    }
                });
                viewHolder.getView(R.id.delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        delItemDialog(bj);
                    }
                });
            }
        });
        adapter.setData(datas);
    }

    private void delItemDialog(final Bj bj) {
        String msg = "户名：" + StringUtil.getNull(bj.getName()) + "\n新表计条形码：" + bj.getBj_new_code();
        new AlertDialog.Builder(this)
                .setTitle("删除表计")
                .setMessage(msg)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (bj.getStatus().equals("1")) {
                            oldDao.setStatus(proId, bj.getCode(), bj.getBj_code());
                        }
                        datas.remove(bj);
                        adapter.notifyDataSetChanged();
                        dialog.dismiss();
                    }
                }).create().show();
    }


    public void click(View v) {
        switch (v.getId()) {
            case R.id.search1:
                Intent intent = new Intent(this, ScannerActivity.class);
                startActivityForResult(intent, 9);
                break;
            case R.id.search2:
                oldList.clear();
                getOldByCode();
                break;
            case R.id.search3:
                String like = search_content.getText().toString();
                if (TextUtils.isEmpty(like)) {
                    ToastUtils.showToast(this, "请输入查询条件");
                    return;
                }
                oldList.clear();
                oldList.addAll(oldDao.selectByLike(proId, like));
                oldAdapter.notifyDataSetChanged();
                break;
//            case R.id.back_btn:
//                finish();
//                break;
            case R.id.back_btn:
            case R.id.save:
                for (Bj b : datas) {
                    if (TextUtils.isEmpty(b.getBj_new_code())) {
                        ToastUtils.showToast(this, "您有未设置新表条码，请先设置");
                        return;
                    }
                }
                bjDao.deleteByBxId(proId, bxId);
                for (Bj b : datas) {
                    b.setBx_id(bxId);
                    bjDao.insert(b);
                }
                save();
                break;
            case R.id.add:
                startActivityForResult(new Intent(this, BjEditeActivity.class), 1);
                break;
        }
    }

    LoadingDialog loadingDialog;

    private void showDialog() {
        if (loadingDialog == null) loadingDialog = new LoadingDialog(this);
        if (!loadingDialog.isShowing()) {
            loadingDialog.setText("正在处理...");
            loadingDialog.show();
        }
    }


    private void closeDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HttpStringUtil.SUCCESSED:
                    JSONObject object0 = JSONObject.parseObject(String.valueOf(msg.obj));
                    if (object0.containsKey("msg")) {
                        ToastShow.showShort(mActivity, object0.getString("msg"));
                    } else {
                        ToastShow.showShort(mActivity, (String) msg.obj);
                    }
                    closeDialog();
                    finish();
                    break;
                case HttpStringUtil.ERROR:
                    closeDialog();
                    JSONObject object99 = JSONObject.parseObject(String.valueOf(msg.obj));
                    if (object99.containsKey("msg")) {
                        ToastShow.showShort(mActivity, object99.getString("msg"));
                    } else {
                        ToastShow.showShort(mActivity, (String) msg.obj);
                    }
                    break;
            }
        }
    };

    void save() {
        showDialog();
        MyApp.HTTP.addBj(handler, HttpStringUtil.SUCCESSED, bxId, JSON.toJSONString(datas));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 9 && data != null) {
            String code = data.getStringExtra("result");
            List<OldBj> list = oldDao.selectByBjCode(proId, code);
            oldList.clear();
            oldList.addAll(list);
            oldAdapter.notifyDataSetChanged();
        } else if ((requestCode == 1 || requestCode == 2) && data != null) {
            Bj b = data.getParcelableExtra("data");
            b.setProId(proId);
            b.setBx_code(new_code);
            b.setBx_code(old_code == null ? "" : old_code);
            if (requestCode == 1) {
                datas.add(b);
            } else if (requestCode == 2) {
                int index = datas.indexOf(editBj);
                datas.remove(editBj);
                datas.add(index, b);
            }
            adapter.notifyDataSetChanged();
        }
    }

    void setOld2New(OldBj o) {
        o.setStatus("1");
        oldDao.update(o);
        Bj b = new Bj();
        b.setGuid(UUID.randomUUID().toString());
        b.setName(o.getName());
        b.setCode(o.getCode());
        b.setAddress(o.getAddress());
        b.setType(o.getType());
        b.setBj_code(o.getBjCode());
        b.setBx_code(o.getBxCode());
        b.setBx_new_code(new_code);
        b.setFactory_code(o.getFactoryCode());
        b.setStatus("1");//选择新增
        oldList.remove(o);
        datas.add(b);
        oldAdapter.notifyDataSetChanged();
        adapter.notifyDataSetChanged();
        setnewCount();
    }

    void setnewCount() {
        int count = datas.size();
        count2.setText(count + "");
    }

}
